package com.example.springboott1.util;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.example.springboott1.entity.AdminUser;

import java.util.Map;

public class JwtUtil {

    private static final String KEY = "dmq";

    public static String createToken(Map<String, Object> payload) {
        DateTime now = DateTime.now();
        DateTime newTime = DateUtil.offsetHour(now,1);

        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);

        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, newTime);

        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);

        String token = JWTUtil.createToken(payload, KEY.getBytes());

        return token;
    }

    public static JWTPayload parseToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        if(!jwt.setKey(KEY.getBytes()).verify()) {
            throw new RuntimeException("token 异常");
        }

        if(!jwt.validate(0)) {
            throw new RuntimeException("token 已过期请重新登录");
        }

        return jwt.getPayload();
    }
}
